package org.arnetminer.personalized.dao;

import java.sql.SQLException;
import java.util.List;

import org.arnetminer.personalized.vo.Source;
import org.arnetminer.personalized.vo.User;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

/**
 	* A data access object (DAO) providing persistence and search support for User entities.
 			* Transaction control of the save(), update() and delete() operations 
		can directly support Spring container-managed transactions or they can be augmented	to handle user-managed Spring transactions. 
		Each of these methods provides additional information for how to configure it for the desired type of transaction control. 	
	 * @see org.arnetminer.personalized.vo.User
  * @author MyEclipse Persistence Tools 
 */

public class UserDAOImpl extends BaseDAOImpl implements UserDAO {
	private static final Logger log = LoggerFactory.getLogger(UserDAOImpl.class);
	//property constants
	public static final String EMAIL = "email";
	public static final String FIRST_NAME = "firstName";
	public static final String LAST_NAME = "lastName";
	
	public void initDao() {
		
		super.initDao();
	}
        
    public User findById(long id) {
        log.debug("getting User instance with id: " + id);
        try {
            User instance = (User) getHibernateTemplate()
                    .get("org.arnetminer.personalized.vo.User", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    
    public List findByProperty(String propertyName, Object value) {
      log.debug("finding User instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from User as model where model." 
         						+ propertyName + "= ?";
		 return getHibernateTemplate().find(queryString, value);
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	public List findByEmail(Object email) {
		return findByProperty(EMAIL, email
		);
	}
	
	public List findByFirstName(Object firstName) {
		return findByProperty(FIRST_NAME, firstName
		);
	}
	
	public List findByLastName(Object lastName) {
		return findByProperty(LAST_NAME, lastName
		);
	}
	

	public List findAll() {
		log.debug("finding all User instances");
		try {
			String queryString = "from User";
		 	return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public void attachClean(User instance) {
		
		super.attachClean(instance);
	}


	public void attachDirty(User instance) {
		
		super.attachDirty(instance);
	}


	public void delete(User persistentInstance) {
		
		super.delete(persistentInstance);
	}


	public List findByExample(User instance) {
		
		return super.findByExample(instance);
	}

	public Object merge(User detachedInstance) {
		
		return super.merge(detachedInstance);
	}

	public void save(User transientInstance) {
		
		super.save(transientInstance);
	}


	public static UserDAOImpl getFromApplicationContext(ApplicationContext ctx) {
    	return (UserDAOImpl) ctx.getBean("UserDAO");
	}

	public List findByProperties(List properties, List values) {
		
		String queryString = "from User as model where";
		String criteria = "";
		for (int i = 0; i < properties.size(); i++) {
			criteria += " AND model." + properties.get(i) + "='" + values.get(i) + "'";
		}
		queryString += criteria.substring(4);
		log.debug("finding User instance with sql:\n" + queryString);
	    try {
	       return getHibernateTemplate().find(queryString);
	    } catch (RuntimeException re) {
	       log.error("find by property name failed", re);
	       throw re;
	    }
	}
	
	public List findByLikeProperties(final List properties, final List values, final int start, final int max) {
		
		log.debug("finding User instance within range\n");
		
	    try {
	    	HibernateTemplate template = getHibernateTemplate();
	    	return template.executeFind(new HibernateCallback() {  
	            public Object doInHibernate(Session session) throws HibernateException, SQLException {
	            	try {
	            	Criteria criteria = session.createCriteria(User.class);
	            	for (int i = 0; i < properties.size(); i++) {
	            		criteria.add(Restrictions.ilike((String) properties.get(i), "%" + values.get(i) + "%"));
	    	    	}
	            	criteria.setFirstResult(start);
	            	criteria.setMaxResults(max);
	            	
	            	return criteria.list();
	            	}
	            	catch (Exception ex) {
	            		ex.printStackTrace();
	            		return null;
	            	}
	            	finally{
	            		session.close();
	            	}
	            }  
	        });
	    } catch (RuntimeException re) {
	       log.error("find by property name failed", re);
	       throw re;
	    }
	}
	
	public int findCountByLikeProperties(final List properties, final List values) {
		
		log.debug("finding User instance within range\n");
		
	    try {
	    	HibernateTemplate template = getHibernateTemplate();
	    	return template.executeFind(new HibernateCallback() {  
	            public Object doInHibernate(Session session) throws HibernateException, SQLException {
	            try{
	            	Criteria criteria = session.createCriteria(User.class);
	            	for (int i = 0; i < properties.size(); i++) {
	            		criteria.add(Restrictions.ilike((String) properties.get(i), "%" + values.get(i) + "%"));
	    	    	}
	            	return criteria.list();
	            }
            	catch (Exception ex) {
            		ex.printStackTrace();
            		return null;
            	}
            	finally{
            		session.close();
            	}
	            } 
	        }).size();
	    } catch (RuntimeException re) {
	       log.error("find by property name failed", re);
	       throw re;
	    }
	}
	
	
	public List validate(String email, String password) {
		
		String queryString = "from User as model left outer join model.security as secu where";
		queryString += " model.email='" + email + "' AND secu.password= ?";
		log.debug("finding User instance with sql:\n" + queryString);
	    try {
	    	return getHibernateTemplate().find(queryString, password);
	    } catch (RuntimeException re) {
	       log.error("find by property name failed", re);
	       throw re;
	    }
	}

	public List findByOrgName(String orgName) {
		log.debug("finding User instance with property: orgName, value: " + orgName);
	      try {
	         String queryString = "from Organization as model where model.orgName" + "= ?";
			 return getHibernateTemplate().find(queryString, orgName);
	      } catch (RuntimeException re) {
	         log.error("find by property name failed", re);
	         throw re;
	      }
		
	}
	
	public Source findSourceById(long id) {
        log.debug("getting Source instance with id: " + id);
        try {
        	Source instance = (Source) getHibernateTemplate()
                    .get("org.arnetminer.personalized.vo.Source", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

}